<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{total}}条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="dialogVisible = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
            <img :src="row.staffPhoto" alt="" style="width:100%">
            </template>
          </el-table-column>
          <el-table-column sortable label="工号" prop="workNumber"  />
          <el-table-column label="聘用形式" >
            <template #default="{row}">
             {{formOfEmploymentPin(row.formOfEmployment)}}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="在职状态" >
            <template #default="{row}">
             {{formOfEmploymentZhi(row.formOfEmployment)}}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <!-- 查询参数 -->
              <!-- <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button> --> 
              <!-- 路径参数,需要用路径接收 -->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="assign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="dele(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="page"
          :page-sizes="[2,5,10,20]"
          :page-size="size"
            background
            layout="total,sizes, pager, next,jumper"
            :total="total">
          </el-pagination>
        </el-row>
      </el-card>
      <!-- 对话框 -->
      <el-dialog
        title="新增员工"
        :visible.sync="dialogVisible"
        width="50%"
        @close="hResetForm">
        <!-- 引入子组件 -->
        <empDialog @close="hSuccess" ref="addEmployees" />
      </el-dialog>
      <!-- 分配角色对话框  -->
      <el-dialog title="分配角色" :visible.sync="assignVisible">
        <assign-role :id="userId" @success="quxiao" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
// 引入子组件
import empDialog from './empDialog.vue'
import { getEmployeelist,deleEmployeelist } from '@/api/employees'
// 引入枚举文件
import Meiemployess from '@/constant/employees'
import AssignRole from '@/views/employees/assignRole.vue'
// 将园数据转换为 {1: '正式', 2: '非正式'} {1: '在职', 2: '离职'} 格式
const hireType = {}
const workingState = {}
Meiemployess.hireType.forEach(item =>{
  hireType[item.id] = item.value
})
Meiemployess.workingState.forEach(item =>{
  workingState[item.id] = item.value
})
// console.log(hireType,workingState);
export default {
  components: { empDialog, AssignRole },
  name:'employess',
  data() {
    return {
      page:1,
      size:2,
      list:[],
      total:0,
      dialogVisible:false,
      assignVisible:false,
      userId:''
    }
  },
  created(){
   this.loadEmployeelist()
  },
  methods:{
    // 取消关闭弹层
    quxiao(){
     this.assignVisible = false
    },
    // 分配按钮
    assign(id){
      this.userId = id
      this.assignVisible = true
    },
    // 将英文转换中文
   formatData(list) {
            const map = {
                'id': '编号',
                'password': '密码',
                'mobile': '手机号',
                'username': '姓名',
                'timeOfEntry': '入职日期',
                'formOfEmployment': '聘用形式',
                'correctionTime': '转正日期',
                'workNumber': '工号',
                'departmentName': '部门',
                'staffPhoto': '头像地址'
            }
            const one = list[0]
            // console.log(one);
            // 如果list中有数组,才需要生成表头
            if(!one) return // 没有数据,直接终止
            const header = Object.keys(one).map(enkey =>{
              return map[enkey]
            })

            // 2.生成data数据
            const data = list.map(item =>{
             return Object.values(item)
            })
            return {header:header,data:data}
        },
    // 导出
   async handleDownload() {
     try {
      // 1. 发送ajax获取数据
      const res = await getEmployeelist(this.page,this.size)
      console.log(res.data.rows);
      // 2. 将数据格式化
     const {header,data} =  this.formatData(res.data.rows)
      // 3. 生成文件
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header:header,
          data:data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
     } catch (error) {
      console.log(error);
     }
    },

    // 重置表单
    hResetForm(){
     this.$refs.addEmployees.resetForm()
    },
    // 监听子组件
    hSuccess(){
      this.dialogVisible = false
      // 分页跳转
      this.total++
      this.page =  Math.ceil(this.total / this.size)
      this.loadEmployeelist()
    },
    // 删除
    dele(id){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await deleEmployeelist(id)
          if(this.list.length === 1){
            this.page--
          }
           this.loadEmployeelist()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 格式化在职状态
    formOfEmploymentZhi(data){
     return workingState[data] || '未知'
    },
    // 格式化聘用形式
    formOfEmploymentPin(data){
     return hireType[data] || '未知'
    },
    //  控制每页显示几条数据
    handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.page = 1
        this.size = val
        this.loadEmployeelist()
      },
    handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.page = val
        this.loadEmployeelist()
      },
    // 获取员工列表数据
  async  loadEmployeelist(){
   const res =  await getEmployeelist(this.page,this.size)
   this.list = res.data.rows
   this.total = res.data.total
  }
  }
}
</script>
